package com.innovation.ic.b1b.monitor.base.service.masterSlave.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.innovation.ic.b1b.monitor.base.mapper.MongodbMapper;
import com.innovation.ic.b1b.monitor.base.model.Mongodb;
import com.innovation.ic.b1b.monitor.base.model.MongodbAvailableJob;
import com.innovation.ic.b1b.monitor.base.pojo.MongodbPojo;
import com.innovation.ic.b1b.monitor.base.pojo.constant.TableNameConstant;
import com.innovation.ic.b1b.monitor.base.pojo.variable.ServiceResult;
import com.innovation.ic.b1b.monitor.base.pojo.variable.mongodb.MongodbInfoRespPojo;
import com.innovation.ic.b1b.monitor.base.service.masterSlave.EnvironmentService;
import com.innovation.ic.b1b.monitor.base.service.masterSlave.MongodbAvailableJobLogHistoryService;
import com.innovation.ic.b1b.monitor.base.service.masterSlave.MongodbAvailableJobLogService;
import com.innovation.ic.b1b.monitor.base.service.masterSlave.MongodbAvailableJobService;
import com.innovation.ic.b1b.monitor.base.service.masterSlave.MongodbService;
import com.innovation.ic.b1b.monitor.base.service.masterSlave.ServiceHelper;
import com.innovation.ic.b1b.monitor.base.vo.MongodbVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class MongodbServiceImpl extends ServiceImpl<MongodbMapper, Mongodb> implements MongodbService {
    @Resource
    private EnvironmentService environmentService;

    @Resource
    private MongodbAvailableJobService mongodbAvailableJobService;

    @Resource
    private MongodbAvailableJobLogService mongodbAvailableJobLogService;


    @Resource
    private MongodbAvailableJobLogHistoryService mongodbAvailableJobLogHistoryService;


    @Resource
    private ServiceHelper serviceHelper;


    @Override
    public ServiceResult addMongodb(MongodbVo mongodbVo) {
        ServiceResult serviceResult = new ServiceResult();
        Integer id = mongodbVo.getId();
        Mongodb mongodb = new Mongodb();
        BeanUtil.copyProperties(mongodbVo, mongodb);
        QueryWrapper<Mongodb> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uri", mongodbVo.getUri());
        if (id == null) {
            List<Mongodb> mongodbList = this.baseMapper.selectList(queryWrapper);
            if (!CollectionUtils.isEmpty(mongodbList)) {
                serviceResult.setSuccess(Boolean.FALSE);
                serviceResult.setMessage("连接字符串重复,请重新添加");
                return serviceResult;
            }

            QueryWrapper<Mongodb> queryWrapperName = new QueryWrapper<>();
            queryWrapperName.eq("name", mongodbVo.getName());
            List<Mongodb> mongodbNameList = this.baseMapper.selectList(queryWrapperName);
            if (!CollectionUtils.isEmpty(mongodbNameList)) {
                serviceResult.setSuccess(Boolean.FALSE);
                serviceResult.setMessage("名字不能重复");
                return serviceResult;
            }
            this.baseMapper.insert(mongodb);
        } else {
            queryWrapper.ne("id", id);
            List<Mongodb> environments = this.baseMapper.selectList(queryWrapper);
            if (!CollectionUtils.isEmpty(environments)) {
                serviceResult.setSuccess(Boolean.FALSE);
                serviceResult.setMessage("连接字符串重复,请重新添加");
                return serviceResult;
            }
            QueryWrapper<Mongodb> queryWrapperName = new QueryWrapper<>();
            queryWrapperName.eq("name", mongodbVo.getName());
            queryWrapperName.ne("id", id);
            List<Mongodb> mongodbNameList = this.baseMapper.selectList(queryWrapperName);
            if (!CollectionUtils.isEmpty(mongodbNameList)) {
                serviceResult.setSuccess(Boolean.FALSE);
                serviceResult.setMessage("名字不能重复");
                return serviceResult;
            }
            this.baseMapper.updateById(mongodb);
        }
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setMessage("成功");
        return serviceResult;
    }

    @Override
    public void deleteMongodb(MongodbVo mongodbVo) {
        Integer id = mongodbVo.getId();
        this.baseMapper.deleteById(id);
        this.deleteByMongodbId(id);
    }

    @Override
    public ServiceResult<PageInfo<MongodbPojo>> findByPage(MongodbVo mongodbVo,Boolean mainDb) {
        ServiceResult<PageInfo<MongodbPojo>> serviceResult = new ServiceResult<>();
        Integer environmentId = mongodbVo.getEnvironmentId();
        if (environmentId != null) {
            List<Integer> environmentIds = environmentService.findByName(environmentId);
            if (!CollectionUtils.isEmpty(environmentIds)) {
                mongodbVo.setEnvironmentIds(environmentIds);
            }
        }
        PageHelper.startPage(mongodbVo.getPageNo(), mongodbVo.getPageSize());
        List<MongodbPojo> environmentPojoList = this.baseMapper.findByPage(mongodbVo);
        PageInfo<MongodbPojo> pageInfo = new PageInfo<>(environmentPojoList);
        serviceResult.setResult(pageInfo);
        serviceResult.setSuccess(Boolean.TRUE);
        return serviceResult;
    }

    /**
     * 查询mongodb信息列表
     *
     * @return 返回查询列表
     */
    @Override
    public ServiceResult<List<MongodbInfoRespPojo>> queryMongodbInfoList(Boolean mainDb) {
        List<MongodbInfoRespPojo> result = this.baseMapper.queryMongodbInfoList();
        ServiceResult<List<MongodbInfoRespPojo>> serviceResult = new ServiceResult<>();
        serviceResult.setResult(result);
        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        return serviceResult;
    }

    @Override
    public void deleteByEnvironmentId(Integer environmentId) {
        QueryWrapper<Mongodb> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("environment_id", environmentId);
        List<Mongodb> mongodbList = this.baseMapper.selectList(queryWrapper);
        for (Mongodb mongodb : mongodbList) {
            this.deleteByMongodbId(mongodb.getId());
        }
        Map<String, Object> map = new HashMap<>();
        map.put("environment_id", environmentId);
        this.baseMapper.deleteByMap(map);
    }


    /**
     * 级联删除关联日志及任务
     * @param mongodbId
     */
    private void deleteByMongodbId(Integer mongodbId){
        List<MongodbAvailableJob> mongodbAvailableJobList = mongodbAvailableJobService.findByMongodbId(mongodbId);
        for (MongodbAvailableJob mongodbAvailableJob : mongodbAvailableJobList) {
            Integer mongodbAvailableJobId = mongodbAvailableJob.getId();
            String jobId = TableNameConstant.MONGODB_AVAILABLE_JOB + "_" + mongodbAvailableJobId;
            serviceHelper.getQuartzManager().deleteScheduleJob(jobId);
            mongodbAvailableJobService.delete(mongodbAvailableJobId);
            //同时删除日志和历史日志
            mongodbAvailableJobLogService.deleteByMongodbAvailableJobId(mongodbAvailableJobId);
            mongodbAvailableJobLogHistoryService.deleteByMongodbAvailableJobId(mongodbAvailableJobId);
        }
    }


}